import axios from 'axios';
import store from '../store'
import { router } from '../router'

export const Axios = axios.create({
    timeout: 15000,
})

Axios.interceptors.request.use(config => {

    if (store.state.token) {
        config.headers.Authorization = store.state.token;
    }
    return config
}, error => {
    alert("错误的传参", 'fail')
    return Promise.reject(error)
})

//返回状态判断(添加响应拦截器)
Axios.interceptors.response.use(res => {
    //对响应数据做些事
    if (res.headers.authorization) {
        store.state.token = res.headers.authorization;
    }

    return res
}, error => {
    if (error.response.status === 401 || error.response.status === 403) {
        // 401 说明 token 验证失败
        // 可以直接跳转到登录页面，重新登录获取 token
        //location.href = '/admin/login'
        router.push('/')
    } else if (error.response.status === 500) {
        // 服务器错误
        // do something
        return Promise.reject(error.response.data)
    }
    // 返回 response 里的错误信息
    return Promise.reject(error.response.data)
})

export default Axios;